package com.jxb.test20241216;

import com.jxb.first.ListNode;

/**
 * 类注释
 *
 * @author jiaobo
 * @date Created in 2024/12/20 19:37
 **/
public class KthFromTail_Offer22 {

    public static void main(String[] args) {

    }

    public static ListNode kthNodeFromEnd(ListNode head , int kthNode){
        ListNode temp = head;
        int length = 0;
        //计算出第k个的节点位置
        while (temp.next != null) {
            length++;
            temp = temp.next;
        }
        int index = length - kthNode + 1;
        //获取第k个元素
        while (head.next != null) {
            if (index <= 0) {
                return head;
            }
            index--;
            head = head.next;
        }
        return null;
    }

    public static ListNode kthNodeFromEnd1(ListNode head , int k){
        ListNode fp = head;
        ListNode sp = head;
        int index = 1;
        while (sp.next != null) {
            fp = fp.next;
            if (index >= k-1) {
                sp = sp.next;
            }
            index++;
        }
        return fp;
    }

}
